Struct
Basic
- 機制是
copy struct
- pointer receiver: 兩個 memory address 是一樣的
package main
import (
"fmt"
)
func main() {
student := Student{Age: 18}
fmt.Printf("memory address: %p\n", &student)
student.change()
fmt.Println(student.Age)
}
type Student struct {
Age int
}
func (student *Student) change() {
student.Age = 25
fmt.Printf("memory address: %p\n", student) // %p -> pointer
}
Anonymous
package main
import (
"fmt"
)
func main() {
// 1.
var test1 struct {
name string
age int
}
test1.age = 15
test1.name = "test"
fmt.Println(test1)
// 2.
test2 := struct {
name string
age int
}{
name: "test",
age: 15,
}
fmt.Println(test2)
}
Embedded
把一個 struct 寫在另一個 struct 裡面,稱作 embedded
(嵌入)
- promoted 被提升 → 外部 struct 可以直接用內部 struct 的 fields
package main
import (
"fmt"
)
func main() {
s := Student{}
s.Age = 27
s.Name.FirstName = "Nano"
s.LastName = "Wang" // 可以直接用 -> promoted
fmt.Println(s)
}
type Student struct {
Name // anonymous field -> embedded
Age int
}
type Name struct {
FirstName string
LastName string
}